package com.shilei.search.service;

import com.shilei.search.util.Punctuate;
import com.shilei.search.word.segmentation.Ansj_;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 石雷
 * shilei1@jiayuan.com
 * 2021/4/1/001 15:26
 */
@Service
public class SearchService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Ansj_ ansj_;

    private Set<String> save(String txt,String tag,String value){
        Set<String> words = ansj_.segOne(txt);
        for (String word : words) {
            //标点符号不建立索引
            if (word.length()==1&&Punctuate.isSymbol(word)){
                continue;
            }
            if(!StringUtils.isEmpty(value)){
                txt=value;
            }
            redisTemplate.opsForZSet().add(tag+word,txt,Double.parseDouble(new Date().getTime()+""));
        }
        return words;
    }

    public Set<String> saveText(String txt){
        String tag="text:";
        return save(txt,tag,null);
    }

    /**
     * 为数据库资源建立索引 内容为 表名_数据id
     * @param txt
     * @param tableName
     * @param id
     * @return
     */
    public Set<String> saveMysql(String txt,String tableName,String id){
        String tag="mysql:";
        return save(txt,tag,tableName+"_"+id);
    }



    private Set<String> query(String word,String tag){
        Set<Object> objs = redisTemplate.opsForZSet().rangeByScore(tag+word, 0, Double.parseDouble(new Date().getTime() + ""));
        Set<String> strs = objs.stream().map(o -> o.toString()).collect(Collectors.toSet());
        return strs;
    }

    public Set<String> queryText(String word){
        return query(word,"text:");
    }

    public Set<String> queryMysql(String word){
        return query(word,"mysql:");
    }
}
